$(function () {
    document.addEventListener('keydown', function (e) {
        if (e.keyCode == 83 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {
            e.preventDefault();
            let status = $("#article-status").val();
            if (status == undefined) {
                postArticle('PUBLISH');
            } else {
                putArticle(status);
            }
        }
    });
});


function postArticle(status) {
    var article = new Object();
    article.title = $("#article-title").val();
    article.content = vditor.getValue();
    article.categoryId = $("input[name='categoryId']:checked").val();
    article.type = $("input[name='type']:checked").val();
    article.tags = $("#article-tags").val();
    article.thumbnail = $("#thumbnail").attr('src');
    article.top = $("#top").prop("checked");
    article.commentAble = $("#commentAble").prop("checked");
    article.status = status;
    post("/articles/infos", article, (status, data, headers) => toast.success(getMessage(headers), reload), (status, data, headers) => toast.failure(getMessage(headers)));
}

function putArticle(status) {
    var article = new Object();
    article.title = $("#article-title").val();
    article.content = vditor.getValue();
    article.categoryId = $("input[name='categoryId']:checked").val();
    article.type = $("input[name='type']:checked").val();
    article.tags = $("#article-tags").val();
    article.thumbnail = $("#thumbnail").attr('src');
    article.top = $("#top").prop("checked");
    article.commentAble = $("#commentAble").prop("checked");
    article.status = status;
    put("/articles/infos/" + $("#article-id").val(), article, 
    	(status, data, headers) => toast.success(getMessage(headers), reload), 
    	(status, data, headers) => toast.failure(getMessage(headers))
    );
}

function setThumbnail(obj) {
    var thumbnail = $(obj).attr("data-obj-thumbnail");
    $("#thumbnail").attr('src', thumbnail);
}

function removeThumbnail() {
    $("#thumbnail").attr('src', "");
    toast.success("封面已经移除！记得要保存哦");
}

function setTag(obj) {
    var $tags = $("#article-tags");
    var tags = $tags.val();
    var text = $(obj).text();
    if (tags.indexOf(text) == -1) {
        $tags.val(tags + text + "；");
    } else {
        if (tags.indexOf(text + ";") != -1) {
            $tags.val(tags.replace(text + ";", ""));
        } else if (tags.indexOf(text + "；") != -1) {
            $tags.val(tags.replace(text + "；", ""));
        } else {
            $tags.val(tags.replace(text, ""));
        }
    }
}

